<template>
  <div class="case-edit">

    <!--编辑修改页-->
    <el-row :gutter="24">
      <!--基本信息、环境选择、请求参数、断言-->
      <el-col :span="16">
        <h3 class="case-title-1" style="margin-bottom: 20px;">基本信息</h3>
        <div>
          <el-form ref="form" label-width="100px">
            <el-row>
              <el-col :span="23">
                <el-form-item label="用例名:" required>
                  <el-input placeholder="用例名" v-model.trim="CaseForm.name"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="11">
                <el-form-item required label="用例编号:">
                  <el-input placeholder="用例编号" v-model.trim="CaseForm.id" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11" :offset="1">
                <el-form-item required label="用例类型:">
                  <el-select placeholder="请选择用例类型" v-model="CaseForm.type">
                    <el-option label="单用例" value="1"></el-option>
                    <el-option label="多用例" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item required label="添加人员:">
                  <el-input placeholder="添加人员" v-model.trim="CaseForm.author"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11" :offset="1">
                <el-form-item required label="请求状态:">
                  <el-select placeholder="请选择请求状态" v-model="CaseForm.expectedStatus">
                    <el-option label="20012121" :value=200></el-option>
                    <el-option label="400" :value=400></el-option>
                    <el-option label="401" :value=401></el-option>
                    <el-option label="404" :value=404></el-option>
                    <el-option label="405" :value=405></el-option>
                    <el-option label="500" :value=500></el-option>
                    <el-option label="502" :value=502></el-option>

                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <h3 class="case-title-1" style="margin-bottom: 20px;">请求环境</h3>
        <div>
          <el-form label-width="100px">
            <el-row>
              <el-col :span="11">
                <el-form-item required label="环境:">
                  <el-select placeholder="请选择环境" v-model="CaseForm.envId">
                    <el-option v-for="(item,index) in envList.list" :value="item.id" :key="index" :label="item.ip"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <h3 class="case-title-1" style=" margin-bottom: 20px;">request</h3>
        <div class="interface-debug-request" style="padding-right: 5px">
          <el-tabs v-model="activeName" type="border-card">
            <!--前置处理-->
            <el-tab-pane label="前置处理" name="first">
              <div class="interface-edit-tabs">
                <el-button icon="el-icon-circle-plus-outline" type="primary" size="mini" style="margin-bottom:3px" @click="addNewPrePressing()">添加</el-button>

                <el-row v-for="(item,index) in preProcessing" :key="index">
                  <el-col :span="8">
                    <el-input placeholder="参数名" v-model.trim="item.name"></el-input>
                  </el-col>
                  <el-col :span="12">
                    <el-input :autosize="{ minRows: 1, maxRows: 4}" placeholder="参数值" v-model.trim="item.value"></el-input>
                  </el-col>
                  <el-col :span="4">
                    <el-button type="primary" size="mini" icon="el-icon-plus" circle @click="addNewPrePressing()"></el-button>
                    <el-button type="danger" size="mini" icon="el-icon-delete" circle v-on:click="preProcessing.splice(index, 1)"></el-button>
                  </el-col>
                </el-row>
              </div>

            </el-tab-pane>
            <el-tab-pane label="请求参数" name="two">
              <div class="interface-edit-tabs">
                <el-button icon="el-icon-circle-plus-outline" type="primary" size="mini" style="margin-bottom:3px" @click="addNewParam()">添加</el-button>
                <el-row v-for="(item,index) in parameters" :key="index">
                  <el-col :span="6">
                    <el-input placeholder="参数名" v-model.trim="item.name"></el-input>
                  </el-col>
                  <el-col :span="4">
                    <el-select placeholder="必填" v-model="item.must">
                      <el-option label="必填" :value=true></el-option>
                      <el-option label="非必填" :value=false></el-option>
                    </el-select>
                  </el-col>
                  <el-col :span="11">
                    <el-input type="textarea" :autosize="{ minRows: 1, maxRows: 3}" placeholder="参数值" v-model.trim="item.value"></el-input>
                  </el-col>
                  <el-col :span="3">
                    <el-button type="primary" size="mini" icon="el-icon-plus" circle @click="addNewParam()"></el-button>
                    <el-button type="danger" size="mini" icon="el-icon-delete" circle v-on:click="parameters.splice(index, 1)"></el-button>
                  </el-col>
                </el-row>
              </div>

            </el-tab-pane>
            <el-tab-pane label="后置处理" name="third">
              <div class="interface-edit-tabs">
                <el-button icon="el-icon-circle-plus-outline" @click="addNewPostPressing()" type="primary" size="mini" style="margin-bottom:3px">添加</el-button>
                <p style="display: inline;font-size: 13px;color: #1a2d8e;">&nbsp;&nbsp;示例（左右正则）：名：secretKey，正则表达式：secretKey\":\"(.*?)\", 有大括号时,需要在前加两个反斜杠</p>
                <el-row v-for="(item,index) in postProcessing" :key="index">
                  <el-col :span="8">
                    <el-input placeholder="参数名" v-model.trim="item.name"></el-input>
                  </el-col>
                  <el-col :span="12">
                    <el-input placeholder="参数值" v-model.trim="item.value"></el-input>
                  </el-col>
                  <el-col :span="4">
                    <el-button type="primary" size="mini" icon="el-icon-plus" circle @click="addNewPostPressing()"></el-button>
                    <el-button type="danger" size="mini" icon="el-icon-delete" circle v-on:click="postProcessing.splice(index, 1)"></el-button>
                  </el-col>
                </el-row>
              </div>
            </el-tab-pane>

            <el-tab-pane label="请求Header" name="fourth">
              <div class="interface-edit-tabs">
                <el-button icon="el-icon-circle-plus-outline" type="primary" size="mini" @click="addNewHeader()" style="margin-bottom:3px">添加</el-button>
                <el-row v-for="(item,index) in headers" :key="index">
                  <el-col :span="8">
                    <el-input placeholder="参数名" v-model.trim="item.name"></el-input>
                  </el-col>
                  <el-col :span="12">
                    <el-input placeholder="参数值" v-model.trim="item.value"></el-input>
                  </el-col>
                  <el-col :span="4">
                    <el-button type="primary" size="mini" icon="el-icon-plus" circle @click="addNewHeader()"></el-button>
                    <el-button type="danger" size="mini" icon="el-icon-delete" circle v-on:click="headers.splice(index, 1)"></el-button>
                  </el-col>
                </el-row>
              </div>
            </el-tab-pane>
            <el-tab-pane label="请求Cookie" name="five">
              <el-button icon="el-icon-circle-plus-outline" type="primary" size="mini" style="margin-bottom:3px">添加</el-button>
            </el-tab-pane>
          </el-tabs>
        </div>

        <h3 class="interface-title-1" style="margin-top: 1rem;margin-bottom:10px">断言</h3>
        <div class="interface-debug-request interface-edit-tabs" style="padding-right: 5px">
          <el-tabs v-model="activeNameExpect" type="border-card">
            <el-tab-pane label="预期结果" name="six">
              <el-input type="textarea" :rows="4" v-model="CaseForm.expectedResult" placeholder="断言" style="margin-bottom:5px"></el-input>

              <div class="interface-edit-tabs">
                <el-row v-for="(item,index) in expectResult" :key="index">
                  <el-col :span="6">
                    <el-select placeholder="断言类型" v-model="item.type">
                      <el-option label="equalTo" value="equalTo"></el-option>
                      <el-option label="containsString" value="containsString"></el-option>
                      <el-option label="notNullValue" value="notNullValue"></el-option>
                      <el-option label="startsWith" value="startsWith"></el-option>
                      <el-option label="endsWith" value="endsWith"></el-option>
                      <el-option label="lessThanOrEqualTo" value="lessThanOrEqualTo"></el-option>
                      <el-option label="greaterThanOrEqualTo" value="greaterThanOrEqualTo"></el-option>
                      <el-option label="hasSize" value="hasSize"></el-option>
                      <el-option label="hasItem" value="hasItem"></el-option>
                      <el-option label="hasItemOrContainsString" value="hasItemOrContainsString"></el-option>
                      <el-option label="hasKey" value="hasKey"></el-option>
                      <el-option label="hasValue" value="hasValue"></el-option>
                    </el-select>
                  </el-col>
                  <el-col :span="7">
                    <el-input placeholder="key" v-model.trim="item.key"></el-input>
                  </el-col>
                  <el-col :span="7">
                    <el-input placeholder="value" v-model.trim="item.value"></el-input>
                  </el-col>
                  <el-col :span="4">
                    <el-button type="primary" size="mini" icon="el-icon-plus" circle @click="addNewRespect()"></el-button>
                    <el-button v-if="index !== 0" type="danger" size="mini" icon="el-icon-delete" circle v-on:click="expectResult.splice(index, 1)"></el-button>
                  </el-col>
                </el-row>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>

        <div style="text-align: center;margin-top: 30px;position: fixed;bottom:0;width:40%;padding-bottom: 15px">
          <el-row>
            <el-button type="primary" icon="el-icon-plus" @click="addCase(CaseForm)" size="small">添加</el-button>
            <el-button type="success" icon="el-icon-refresh-left" @click="updateCase(CaseForm)" size="small">更新</el-button>
            <el-button type="warning" icon="el-icon-caret-right" @click="executeDebugCase()" size="small">调试</el-button>
            <el-button type="danger" icon="el-icon-finished" @click="expectParamObjectCopy(expectResult)" size="small">生成断言</el-button>
          </el-row>
        </div>

      </el-col>

      <!--请求url、请求header、请求cookie、返回结果-->
      <el-col :span="8">
        <h3 class="case-title-1" style="margin-bottom: 20px;">response</h3>

        <div>
          <p class="interface-debug-p" style="margin-top:1px;">请求url：</p>
          <pre class="span12" style="border:1px solid;height: 140px;font-size:13px;border-radius: 4px;" contenteditable="true" v-html="caseExecuteDebugList.url"></pre>
          <p class="interface-debug-p" style="margin-top:14px;">headers：</p>
          <pre class="span12" style="border:1px solid;height: 180px;font-size:13px;border-radius: 4px;" contenteditable="true" v-html="caseExecuteDebugList.headers"></pre>
          <p class="interface-debug-p" style="margin-top:14px">response：</p>
          <span style="font-size:12px">{{caseExecuteDebugList.result}}</span>

          <div class="deep">
            <el-form label-width="50px" label-position="left">
              <el-form-item label="deep:">
                <el-select v-model="deep" placeholder="请选择">
                  <el-option :key="1" :label="1" :value="1"> </el-option>
                  <el-option :key="2" :label="2" :value="2"> </el-option>
                  <el-option :key="3" :label="3" :value="3"> </el-option>
                  <el-option :key="4" :label="4" :value="4"> </el-option>
                  <el-option :key="5" :label="5" :value="5"> </el-option>
                  <el-option :key="6" :label="6" :value="6"> </el-option>
                  <el-option :key="7" :label="7" :value="7"> </el-option>
                  <el-option :key="8" :label="8" :value="8"> </el-option>
                  <el-option :key="9" :label="9" :value="9"> </el-option>
                  <el-option :key="10" :label="10" :value="10"> </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          <div>
            <json-view :data="caseExecuteDebugList.json" icon-style="square" style="min-height:400px" theme="one-dark" :font-size="13" :line-height="22" :deep="deep" />
          </div>

          <p class="interface-debug-p" style="margin-top:14px">后置处理：</p>
          <pre class="span12" style="border:1px solid;height: 180px;font-size:13px;margin-bottom: 15px;    border-radius: 4px;" contenteditable="true" v-html="caseExecuteDebugList.postProcessing"></pre>
        </div>

      </el-col>
    </el-row>

  </div>

</template>

<script>
import qs from "qs";
import jsonView from "vue-json-views";
import vueJsonEditor from "vue-json-editor";
import { getEnv, deleteEnv, updateEnv } from '@/api/env'
import { addCase, getCase, deleteCase, updateCase, executeDebugCase } from '@/api/case'
import { isNull, isEmpty, isIntNum } from "@/utils/baseUtil";
export default {
  data () {


    return {
      activeName: 'two',
      activeNameExpect: "six",
      deep: 2,

      //接口提交表单
      interfaceForm: {},
      //单条用例信息
      CaseForm: {
        caseName: "",
        type: "1",
        expectedStatus: 200,
        author: "曹森泉",
        groupId: 1,
        envId: "",
        expectedResult: ""
      },

      caseExecuteDebugList: {
        status: "",
        result: "",
        url: "",
        secretKey: "",
        cookies: "",
        postProcessing: "",
        json: {},
      },



      envList: {
        projectId: this.$store.state.projectId,
        ip: "请选择ip地址",
        list: []
      },

      expectResult: [{ type: "equalTo", key: "", value: "" }],
      parameters: [],
      publicParameters: [],
      headers: [],
      preProcessing: [],
      postProcessing: [],



    }
  },

  components: {
    vueJsonEditor,
    jsonView
  },


  methods: {
    //获取项目下环境信息
    getEnvByProjectId (projectId) {
      getEnv(projectId, '', '', 1, 1000).then(resp => {
        if (resp.code == 200) {
          this.envList.list = resp.data.records
        }
      })
    },

    //获取用例  在case组件里边调用
    getCase (caseId) {
      var self = this;
      getCase('', caseId, 1, 100).then(resp => {
        self.CaseForm = resp.data.records[0];
        self.CaseForm.type = "1"
        console.log(self.CaseForm)
        //类型转换
        self.parameters = self.jsonToListTo(JSON.parse(self.CaseForm.params));
        // self.publicParameters = self.jsonToListTo(JSON.parse(resp.data.data.publicParameters));
        self.headers = self.jsonToListTo(self.CaseForm.headers == "" ? "" : JSON.parse(self.CaseForm.headers));
        self.preProcessing = self.jsonToListTo(JSON.parse(self.CaseForm.preProcessing));
        self.postProcessing = self.jsonToListTo(JSON.parse(self.CaseForm.postProcessing));
        console.log(self.CaseForm)
      })
    },

    //添加用例
    addCase (CaseForm) {
      //请求参数
      this.CaseForm.params = this.listToJson(this.parameters);
      //请求头
      this.CaseForm.headers = this.listToJson(this.headers);
      //后置处理
      this.CaseForm.postProcessing = this.listToJson(this.postProcessing);
      //前置处理
      this.CaseForm.preProcessing = this.listToJson(this.preProcessing);

      addCase(CaseForm).then(resp => {
        if (resp.code == 200) {
          this.$emit("getInterfaceCase", this.CaseForm.apiId, 1, 1000);
          this.$message({
            message: resp.message,
            type: "success"
          });
        }
      })
    },

    //更新用例
    updateCase (CaseForm) {
      //请求参数
      this.CaseForm.params = this.listToJson(this.parameters);
      //请求头
      this.CaseForm.headers = this.listToJson(this.headers);
      //后置处理
      this.CaseForm.postProcessing = this.listToJson(this.postProcessing);
      //前置处理
      this.CaseForm.preProcessing = this.listToJson(this.preProcessing);
      updateCase(CaseForm).then(resp => {
        if (resp.code == 200) {
          this.$emit("getInterfaceCase", this.CaseForm.apiId, 1, 1000);
          this.$message({
            message: resp.message,
            type: "success"
          });

        }
      })
    },


    //调试用例
    executeDebugCase () {
      this.CaseForm.interfaceId = this.interfaceForm.id;
      this.CaseForm.requestType = this.interfaceForm.requestType;

      this.CaseForm.caseName = this.CaseForm.name
      this.CaseForm.author = "aitesting"
      this.CaseForm.envId = 102
      this.CaseForm.interfaceId = 1761
      this.CaseForm.groupId = 217
      //请求参数
      this.CaseForm.parameters = this.listToJson(this.parameters);
      //请求头
      this.CaseForm.headers = this.listToJson(this.headers);
      //后置处理
      this.CaseForm.postProcessing = this.listToJson(this.postProcessing);
      //前置处理
      this.CaseForm.preProcessing = this.listToJson(this.preProcessing);
      executeDebugCase(qs.stringify(this.CaseForm)).then(resp => {
        this.caseExecuteDebugList.json = JSON.parse(resp.response);
        console.log(this.caseExecuteDebugList.json)
        this.caseExecuteDebugList.url = resp.url;
        this.caseExecuteDebugList.status = resp.status;
        this.caseExecuteDebugList.headers = resp.headers;
        this.caseExecuteDebugList.result = resp.message +
          "\r状态：" + resp.status +
          "\r时长：" + resp.time + "ms"
        "\r" +
          resp.response;

      })
    },

    //断言生成
    expectParamObjectCopy (params) {
      console.log(params)
      var param_str = "";
      var obj = {};
      for (var i = 0; i < params.length; i++) {
        console.log(12345)
        var expect_type = params[i].type;
        //如果为数字去掉引号
        if (isIntNum(params[i].value)) {
          var expect_value = parseInt(params[i].value);
        } else {
          var expect_value = params[i].value;
        }
        var expect_name = params[i].key;
        if (expect_type != "") {
          if (obj[expect_type]) {
            obj[expect_type][expect_name] = expect_value;
          } else {
            obj[expect_type] = {};
            obj[expect_type][expect_name] = expect_value;
          }
        }
        this.CaseForm.expectedResult = JSON.stringify(obj);
        return JSON.stringify(obj);
      }
    },






    //将json的key的value赋值给list的值
    jsonToListTo (json) {
      var list = [];
      for (var key in json) {
        list.push({
          name: key,
          value: json[key].replace(/\"/g, '\\"')
        });
      }
      return list;
    },

    //list转json
    listToJson (params) {
      var param_str = "";
      if (params == "" || params == null) {
        params = [];
      }
      for (var i = 0; i < params.length; i++) {
        //循环LIST
        if (i == params.length - 1) {
          param_str += '"' + params[i].name + '":"' + params[i].value + '"';
        } else {
          param_str += '"' + params[i].name + '":"' + params[i].value + '",';
        }
      }
      if (param_str != "") {
        param_str = "{" + param_str + "}";
      }
      return param_str;
    },

    syntaxHighlight () {

    },
    //添加参数
    addNewParam () {
      if (this.parameters == null) {
        this.parameters = [];
      }
      this.parameters.push({
        name: "",
        must: true,
        remark: "",
        type: "string",
        value: ""
      });
    },

    //添加公共参数
    addNewCommonParam () {
      if (this.publicParameters == null) {
        this.publicParameters = [];
      }
      this.publicParameters.push({
        name: "",
        must: true,
        remark: "",
        value: "",
        type: "string"
      });
    },

    //添加header
    addNewHeader () {
      if (this.headers == null) {
        this.headers = [];
      }
      this.headers.push({
        name: "",
        value: "",
        remark: ""
      });
    },

    //添加预期结果
    addNewRespect () {
      if (this.expectResult == null) {
        this.expectResult = [];
      }
      this.expectResult.push({
        type: "equalTo",
        key: "",
        value: ""
      });
    },

    //添加前置处理
    addNewPrePressing () {
      if (this.preProcessing == null) {
        this.preProcessing = [];
      }
      this.preProcessing.push({ name: "", value: "" });
    },

    //添加后置处理
    addNewPostPressing () {
      if (this.postProcessing == null) {
        this.postProcessing = [];
      }
      this.postProcessing.push({ name: "", value: "" });
    },
  },

  mounted () {
    this.getEnvByProjectId(this.$store.state.projectId);
  }
}
</script>

<style scoped>
.case-title-1 {
  clear: both;
  font-weight: 400;
  margin-top: 0.4rem;
  border-left: 3px solid #2395f1;
  padding-left: 8px;
  display: inline-block;
}

.case-edit .interface-edit-tabs >>> .el-row {
  padding-bottom: 6px;
}
.case-edit .interface-edit-tabs >>> .el-col {
  padding-right: 6px;
}

.interface-edit-tabs >>> .el-button--mini.is-circle {
  padding: 5px;
}

.case-edit p {
  margin-bottom: 1px;
  font-size: 14px;
  font-weight: 500;
}

.case-edit pre {
  margin-top: 1px;
}

.deep .el-form-item {
  margin-bottom: 1px;
}

.case-edit >>> .el-button + .el-button {
  margin-left: 1px;
}
</style>